<template>
  <div v-loading="detailInfoShow">
    <div
      class="requestAdd"
      v-if="
        !selectionMaterialShow &&
        !requestAddShow &&
        !paymentAddShow &&
        !inorderAddShow
      "
    >
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check'"
          class="btn save"
          @click="handleCheckBtn2('', 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check'"
          class="btn withdraw"
          @click="handleCheckBtn2('', 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check'"
          class="btn withdraw"
          @click="handleCheckBtn2('', 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >提交</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button
          v-if="
            pageType === 'detail' &&
            requestForm.contractCheckStatus === 3 &&
            route.name === 'ServeContract' &&
            requestForm.contractType !== 2 &&
            requestForm.supplement !== 1
          "
          class="btn add"
          @click="handleAddPayment()"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >申请付款</el-button
        >
        <el-button
          v-if="
            pageType === 'detail' &&
            requestForm.contractCheckStatus === 3 &&
            route.name === 'ServeContract' &&
            requestForm.contractType !== 2 &&
            requestForm.supplement !== 1
          "
          class="btn add"
          @click="handleAddTicket()"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增到票</el-button
        >

        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-collapse v-model="activeNames">
        <!-- 基础信息 -->
        <el-collapse-item
          name="1"
          v-if="!contactAddShow"
          class="transform-down"
        >
          <template #title>
            <span class="circle"></span>
            <span class="collapse-title"
              >{{
                pageType == "detail" || pageType == "check"
                  ? ""
                  : pageType === "add"
                  ? "新增"
                  : "编辑"
              }}合同用印信息</span
            >
          </template>
          <div class="request-info">
            <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="130px"
              v-enterToNext
              :disabled="pageType === 'detail' || pageType === 'check'"
            >
              <el-row>
                <el-col :span="6">
                  <el-form-item label="合同编号：">
                    <el-input
                      disabled
                      v-model="requestForm.purchaseContractCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="合同名称：" prop="purchaseContractName">
                    <el-input
                      v-model="requestForm.purchaseContractName"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      maxlength="50"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                
                >
                  <el-form-item label="合同内容：" prop="conContent">
                    <el-input
                      maxlength="200"
                      v-model="requestForm.conContent"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期：" prop="applicantDate">
                    <el-date-picker
                      v-model="requestForm.applicantDate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办人：" prop="applicantId">
                    <el-select
                      filterable
                      v-model="requestForm.applicantId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUserChange"
                      value-key="userId"
                      placement="bottom-end"
                    >
                      <!-- <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :label="dict.nickName"
                        :value="dict.userId"
                      /> -->
                      <el-option disabled :value="null">
                        <div class="auto-top">
                          <span class="auto-item">人员姓名</span>
                          <span class="auto-item">联系方式</span>
                          <span class="auto-item">职位</span>
                          <span class="auto-item">部门</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :value="dict.userId"
                        :label="dict.nickName"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.nickName">
                            {{ dict.nickName }}
                          </div>
                          <div class="auto-item" :title="dict.phonenumber">
                            {{ dict.phonenumber ? dict.phonenumber : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.postName">
                            {{ dict.postName ? dict.postName : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.fullDeptName">
                            {{ dict.fullDeptName ? dict.fullDeptName : "--" }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办部门：">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>

          
              
                <el-col
                  :span="6"
              
                >
                  <el-form-item label="甲方单位：" prop="customerId">
                    <el-select
                      :placeholder="'请选择'"
                      placement="bottom-end"
                      v-model="requestForm.customerId"
                      clearable
                      class="search-input"
                    >
                    <el-option
                      v-for="dict in customerList"
                      :key="dict.customerId"
                      :label="dict.name"
                      :value="dict.customerId"
                    />
                    </el-select>
                  </el-form-item>
                </el-col>
            

                <el-col
                  :span="6"
                >
                  <el-form-item label="印章归属：" prop="ownershipSeal">
                    <el-select
                      :placeholder="'请选择'"
                      placement="bottom-end"
                      v-model="requestForm.ownershipSeal"
                      clearable
                      class="search-input"
                    >
                      <el-option
                        v-for="dict in partyUnitsList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

               

                
                
                <el-col :span="6">
                  <el-form-item label="合同金额：" prop="contractAmount">
                    <el-input
                      type="Number"
                      v-model="requestForm.contractAmount"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
             
                <el-col
                  :span="6"
                >
                  <el-form-item label="用印文件：" prop="printedDocuments">
                    <el-input
                      type="Number"
                      v-model="requestForm.printedDocuments"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      :max="99"
                    >
                      <template #append>份</template>
                    </el-input>
                  </el-form-item>
                </el-col>
             
               
                <el-col :span="6">
                  <el-form-item label="应归档份数：" prop="pigeonholeNumber">
                    <el-input
                      v-model="requestForm.pigeonholeNumber"
                      type="Number"
                      placeholder="请输入"
                      clearable
                      :max="99"
                      class="search-input"
                    >
                      <template #append>份</template></el-input
                    >
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                
                >
                  <el-form-item label="合同备注：" prop="remarks">
                    <el-input
                      maxlength="200"
                      v-model="requestForm.remarks"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                    <el-col
                      :span="6"
                    >
                      <el-form-item label="合同附件：" prop="suppFileInfoVos">
                        <Upload
                          :fileList="requestForm.suppFileInfoVos"
                          :isFull="true"
                          :limit="10"
                          :showButton="true"
                          @success="(result) => uploadSuccess(result)"
                          @deleteFile="(result) => uploadRemove(result)"
                          :isCanDelete="pageType == 'detail' ? false : true"
                          :disabled="pageType == 'detail'"
                        />
                        <!-- accept=".jpg,.png" -->
                      </el-form-item>
                    </el-col>
                  </el-row>
             
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <!-- 选择物料 -->
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      :RequestChooseList="requestForm.purchaseContractMaterialRespVos"
      :materialAllList="materialAllList"
      :purchaseOrderId="requestForm.purchaseOrderId"
      @submitChoose="handleSelectMaterial"
    />
   

    <!-- 归档默认0 弹窗 -->
    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 归档1 提交申请人 弹窗 -->
    <el-dialog
      :title="auditDialog1Showtitle"
      v-model="auditDialog1Show"
      width="1000px"
      append-to-body
    >
      <Subapplicant
        v-if="auditDialog1Show"
        @closeauditDialog1="closeauditDialog1"
        @handleBack="handleBack"
        :requestForm="requestForm"
        modeltype="serveContract"
      ></Subapplicant>
    </el-dialog>
    <!-- 归档2 合同保管员 弹窗 -->
    <el-dialog
      :title="auditDialog2Showtitle"
      v-model="auditDialog2Show"
      width="1000px"
      append-to-body
    >
      <Contractcustodian
        v-if="auditDialog2Show"
        @closeauditDialog2="closeauditDialog2"
        @handleBack="handleBack"
        :requestForm="requestForm"
        modeltype="serveContract"
      ></Contractcustodian>
    </el-dialog>
  </div>
</template>

<script setup>
import RequestAdd from "./requestAdd.vue";
import PaymentAdd from "../../purchase/payment/requestAdd.vue";
import InorderAdd from "../../stock/inorder/add.vue";
import Subapplicant from "../../seal/circulation/subapplicant";
import Contractcustodian from "../../seal/circulation/contractcustodian";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import { getUserListApi } from "@/api/information/customer";
import useUserStore from "@/store/modules/user";
// import { getProjectListApi } from "@/api/sales/project";
import {
  getSealListApi,
  getRawSealListApi,
  getOrderListApi,
  getOrderMaterialApi,
  getTicketListApi,
  getInorderListApi,
  deleteTicketApi,
  getFrameSelectListApi,
  getFrameDetailListApi,
  getProjectListApi,
} from "@/api/purchase/contractSeal";
import {
  checkSealApi,
  getSourceContract,
  getSealDetailApi,
  getPropertyListAPi,
  addSealApi,
  editSealApi,
} from "@/api/serve/contractSeal";
import {
  getCustomerAllListApi,
} from "@/api/information/customer";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
import { deletePaymentId } from "@/api/purchase/payment";
import { nextTick } from "vue";

const route = useRoute();
const userStore = useUserStore();
const emit = defineEmits([
  // 客户新增组件显隐
  "contractSealAddShow",
  // 更新客户新增组件显隐
  "update:contractSealAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
const contentType = ref(6)
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5", "6", "7"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
const inputRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);

// 选择审核
const auditDialogShow = ref(false);

let auditDialog1Show = ref(false);
let auditDialog1Showtitle = ref("");
let auditDialog2Show = ref(false);
let auditDialog2Showtitle = ref("");
const loadingCheck = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 合同类型列表
const typeList = ref([]);
// 发票类型
const invoiceTypeList = ref([]);

// 采购类型列表
const purchaseDefaultList = ref([]);
const purchaseTypeList = ref([]);
// 甲方单位
const customerList = ref([]);
const partyUnitsList = ref([]);
// 知识产权列表
const propertyList = ref([]);
// 单位列表
const unitList = ref([]);
// 采购订单列表
const orderList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 解除列表
const relieveList = ref([]);
// 项目列表
const projectList = ref([]);
// 请购列表
const requestList = ref([]);
const requestAllList = ref([]);
const requestFilterList = ref([]);
// 采购物料列表
const materialAllList = ref([]);
// 原合同列表
const sourceContractList = ref([]);
const sourceContractList2 = ref([]);
// 合同用印到票列表
const ticketList = ref([]);
// 付款列表
const paymentList = ref([]);
// 入库列表
const inorderList = ref([]);
// 框架协议列表
const frameList = ref([]);
// 到票操作类型
const ticketPageType = ref("");
// 付款操作类型
const paymentPageType = ref("");
// 入库操作类型
const inorderPageType = ref("");
// 客户新增组件显隐
const requestAddShow = ref(false);
// 付款新增组件显隐藏
const paymentAddShow = ref(false);
// 入库新增组件显隐藏
const inorderAddShow = ref(false);
// 到票新增组件引用
const requestAddRef = ref(null);
// 合同用印id
const sealId = ref(null);
//渠道列表
const channelList = ref([]);
// 默认税率列表
const taxRateList = ref([]);

const paymentAddRef = ref(null);
//关联项目名称信息
const projectInfo = ref("");

// 客户表单数据模板
const requestFormTemplate = {
  purchaseContractCode: "", // 合同编号
  purchaseContractName: "", // 合同名称
  conContent: "", // 合同内容
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  customerId: null, // 甲方单位
  ownershipSeal: null, // 印章归属
  contractAmount: null, // 合同金额
  printedDocuments: null, // 用印文件
  pigeonholeNumber: null, // 应归档份数
  remarks: "", // 备注
  type: 0, // 	按钮类型0：存为草稿；1；提交
  deptName: "", // 申请部门
  suppFileInfoVos:[]
 
};
// 联系人表单数据模板
const contactFormTemplate = {
  deliveryCycle: "", // 到货周期
  factoryCode: "", // 出厂编号
  manufactureName: "", // 生产厂商名称
  manufacturerId: null, // 生产厂商(也是供应商id)
  manufacturerIdName: "", // 生产厂商全称（详情专用）
  materialCode: "", // 	物料编号
  materialName: "", // 	物料名称
  materialUnit: null, // 	物料单位
  materialUnitName: "", // 物料单位中文
  purchaseApplyId: null, // 关联请购申请表主键id
  purchaseMaterialId: null,
  purchaseNumber: null, // 请购数量
  purchasePrice: null, // 	请购单价
  allPrice: null, // 总价
  purchaseTrackingStatus: null, // 请购跟踪状态
  purchaseTrackingStatusName: "", // 	请购跟踪状态中文
  referenceLink: "", // 参考链接
  remarks: "", // 备注
  suppFileInfoVos: [], // 采购申请物料图片
  supplierId: null, // 供应商id
  supplierIdName: "", // 供应商全称（详情专用）
  supplierName: "", // 供应商名称
  technologyParameter: "", // 技术参数
  channel: null, //渠道
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [{ required: true, message: "请选择经办人", trigger: "change" }],
    conContent: [
      { required: true, message: "请输入合同内容", trigger: "blur" },
    ],
    purchaseContractName: [
      { required: true, message: "请输入合同名称", trigger: "blur" },
    ],
    ownershipSeal: [
      { required: true, message: "请选择印章归属", trigger: "change" },
    ],
    purchaseContractName: [
      { required: true, message: "请输入合同名称", trigger: "blur" },
    ],
    supplierName: [
      { required: true, message: "请输入供应商", trigger: "change" },
    ],
    customerId: [
      { required: true, message: "请选择甲方单位", trigger: "change" },
    ],
    contractAmount: [
      { required: true, message: "请输入合同金额", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 9999999999 || value < -9999999999) {
            callback(new Error("最大可输入十位数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
    sourceContractName: [
      { required: true, message: "请选择原合同", trigger: "change" },
    ],
    sourceContract: [
      { required: true, message: "请选择原合同", trigger: "change" },
    ],
    secureReason: [
      { required: true, message: "请选择解除原因", trigger: "change" },
    ],
    printedDocuments: [
      { required: true, message: "请选择用印文件", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (value < 1 || value > 99) {
            callback(new Error("用印文件为0到99之间的整数"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    pigeonholeNumber: [
      { required: true, message: "请输入应归档份数", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 1 || value > 99) {
            callback(new Error("应归档份数为0到99之间的整数"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
  
    suppFileInfoVos: [
      { required: true, message: "请上传合同附件", trigger: "change" },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      {
        required: true,
        message: "请输入物料名称",
        trigger: ["blur", "change"],
      },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入采购数量", trigger: "blur" },
    ],
    budgetedPrice: [
      { required: true, message: "请输入预算单价", trigger: "blur" },
    ],
    purchasePrice: [
      { required: true, message: "请输入询价单价", trigger: "blur" },
    ],
    taxRate: [{ required: true, message: "请输入税率", trigger: "blur" }],
    freight: [
      { required: true, message: "请输入运费", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value > 999999 || value < 0) {
            callback(new Error("运费为0到999999之间的数字"));
          } else {
            if (value.toString().split(".")[1]?.length > 2) {
              callback(new Error("运费小数点后最多两位"));
            } else {
              callback();
            }
          }
        },
      },
    ],
  
  },
  // 角色列表
  contactTypeList: [],
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
  auditRemark,
  auditResult,
  applyId,
} = toRefs(data);

const handleCheckBtn2 = (requestFormRef, type, title) => {
  if (type == 3) {
    switch (requestForm.value.nextAudit.flowIntype) {
      case "0":
        auditRemark.value = "同意";
        auditResult.value = type;
        applyId.value = requestForm.value.purchaseContractId;
        auditDialogShow.value = true;
        loadingCheck.value = false;
        break;
      case "1":
        //提交申请人
        auditDialog1Show.value = true;
        auditDialog1Showtitle.value = "资料归档";
        break;
      case "2":
        //合同保管人
        auditDialog2Show.value = true;
        auditDialog2Showtitle.value = "资料归档";
        break;

      default:
        break;
    }
  } else {
    auditRemark.value = "";
    auditResult.value = type;
    applyId.value = requestForm.value.purchaseContractId;
    auditDialogShow.value = true;
    loadingCheck.value = false;
  }
};
const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  const obj = {
    contractCheckStatus: auditResult.value,
    purchaseContractId: applyId.value,
    auditRemark: auditRemark.value,
    contractType: requestForm.value.contractType,
    // oldPurchaseContractId:requestForm.value.sourceContract
  };
  try {
    loadingCheck.value = true;
    const res = await checkSealApi(obj);
    auditDialogShow.value = false;

    //loadingCheck.value =false;

    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
    emit("update:contractSealAddShow", false);
    emit("refreshList", false);
  } catch (error) {
    loadingCheck.value = false;
    emit("update:contractSealAddShow", false);
    emit("refreshList", false);
    // ElMessage.error(error);
  }
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

const closeauditDialog1 = () => {
  console.log('close1')
  auditDialog1Show.value = false;
};

const closeauditDialog2 = () => {
   console.log('close2')
  auditDialog2Show.value = false;
};

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          requestForm.value.type = type;
          requestForm.value.contractType = contentType.value;
          let res;
          if (!requestForm.value.purchaseContractId) {
            // 新增客户
            res = await addSealApi(requestForm.value);
          } else {
            // 编辑客户
            res = await editSealApi(requestForm.value);
          }
          if (res.code === 200) {
            emit("update:contractSealAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:contractSealAddShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:contractSealAddShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  requestForm.contractType;
  if (requestForm.value.contractType !== null) {
    selectionMaterialShow.value = true;
  } else {
    ElMessage.warning("请先选择合同类型");
  }
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value.length) {
    requestForm.value.purchaseContractMaterialRespVos.push(...value);
    selectionMaterialShow.value = false;
    if (requestForm.value.purchaseOrderId) {
    }
  } else {
    ElMessage.info("请选择物料");
  }
};
/* 选择渠道 */
const changeChannel = (row) => {
  var obj = {};
  obj = channelList.value.find(function (i) {
    return i.value === row;
  });
  contactForm.value.channelName = obj.label;
};

/**
 * @description: 处理供应商、生产厂家选择
 */
// const handleSuppliereSelect = (value, index) => {
//   if (index == 1) {
//     contactForm.value.supplierId = value.supplierId;
//   } else {
//     requestForm.value.supplierId = value.supplierId;
//   }
// };

// const querySearch = (queryString, cb) => {
//   const results = queryString
//     ? suppliereList.value.filter(createFilter(queryString))
//     : suppliereList.value;
//   cb(results);
// };
/* 原合同input框搜索 */
const contractSearch = (queryString, cb) => {
  const results = queryString
    ? sourceContractList.value.filter(createFilter(queryString))
    : sourceContractList.value;
  cb(results);
};

/* 关联采购单input框搜索 */
const purchaseSearch = (queryString, cb) => {
  let results = queryString
    ? orderList.value.filter(createFilter(queryString))
    : orderList.value;
  if (queryString == "null") {
    results = orderList.value;
  }
  cb(results);
};
/* 关联采购单下拉框 */
const handlePurchaseSelect = (value) => {
  if (value.checkMaterialStatus == 1) {
    requestForm.value.purchaseOrderId = value.purchaseOrderId;
    handleOrderChange(value.purchaseOrderId);
  } else {
    requestForm.value.purchaseOrderId = null;
    requestForm.value.purchaseOrderCode = null;
    inputRef.value.blur();
    ElMessage.warning("请前往采购订单管理，完善物料后再新增合同信息");
  }
};

const handlePurchaseChange = (value) => {
  if (!value) {
    requestForm.value.purchaseOrderId = null;
    requestForm.value.purchaseOrderCode = null;
  }
};

const handleContractSelect = (value) => {
  requestForm.value.sourceContract = value.purchaseContractId;
  requestForm.value.supplierName = value.distributorName;
  requestForm.value.supplierId = value.supplierId;
};

const handleContractSelect2 = (value) => {
  // if () {
  if (value) {
    sourceContractList2.value.forEach((item) => {
      if (item.purchaseContractId == value) {
        console.log("匹配");
        console.log(item);
        requestForm.value.supplierName = item.distributorName;
        requestForm.value.supplierId = item.supplierId;
        requestForm.value.startDate = item.startDate;
        requestForm.value.expirationDate = item.expirationDate;
        requestForm.value.serviceTime = item.serviceTime;
        requestForm.value.customerId = item.customerId;
        requestForm.value.contractAmount = item.contractAmount;
        if ([1].includes(requestForm.value.contractType)) {
          requestForm.value.purchaseType = item.purchaseType;
          requestForm.value.intellectualPropertyId =
            item.intellectualPropertyId;
          requestForm.value.purchaseUse = item.purchaseUse;
        }
      }
    });
  } else {
    requestForm.value.supplierName = "";
    requestForm.value.supplierId = null;
    requestForm.value.startDate = "";
    requestForm.value.expirationDate = "";
    requestForm.value.serviceTime = "";
    requestForm.value.customerId = null;
    requestForm.value.contractAmount = "";
    requestForm.value.purchaseType = null;
    requestForm.value.intellectualPropertyId = null;
    requestForm.value.purchaseUse = null;
    requestForm.value.contractAmount = "";
  }
  // }
};

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const obj = {
        contractCheckStatus: type,
        purchaseContractId: requestForm.value.purchaseContractId,
        purchaseInqMaterialDetailLitsRespVos:
          requestForm.value.purchaseInqMaterialDetailLitsRespVos,
        purchaseOrderId: requestForm.value.purchaseOrderId,
      };
      const res = await checkSealApi(obj);
      if (res.code === 200) {
        emit("update:contractSealAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleType = (value) => {
  requestForm.value = {
    ...requestFormTemplate,
    purchaseContractCode: requestForm.value.purchaseContractCode,
    synthesisContractName: requestForm.value.synthesisContractName,
    applicantDate: requestForm.value.applicantDate,
    handleId: requestForm.value.handleId,
    deptName: requestForm.value.deptName,
    contractType: requestForm.value.contractType,
  };
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      console.log(selectUser);
      requestForm.value.deptName = selectUser.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理采购单选择
 * @param {Number} value 选择值
 */
const handleSupplierChange = async (value) => {
  requestForm.value.frameworkId = null;
  requestForm.value.purchaseConMaterialByIdRespVos = [];
  if (value) {
    // 框架协议
    await getFrameSelectListApi(value).then((res) => {
      if (res) {
        frameList.value = res;
      }
    });
  } else {
    frameList.value = [];
  }
};

/**
 * @description: 处理框架协议选择
 * @param {Number} value 选择值
 */
const handleFrameChange = async (value) => {
  // requestForm.value.frameworkId = null
  if (value) {
    frameList.value.forEach((item) => {
      if (item.purchaseContractId === value) {
        requestForm.value.purchaseContractCode = item.purchaseContractCode;
      }
    });
    // 框架协议
    await getFrameDetailListApi(value).then((res) => {
      if (res) {
        requestForm.value.purchaseConMaterialByIdRespVos = res;
      }
    });
  } else {
    requestForm.value.purchaseConMaterialByIdRespVos = [];
  }
};

/**
 * @description: 处理采购单选择
 * @param {Number} value 选择值
 */
const handleOrderChange = async (value) => {
  // 回显物料信息
  const res = await getOrderMaterialApi({
    contractType: requestForm.value.contractType,
    purchaseOrderId: requestForm.value.purchaseOrderId,
  });
  if (res) {
    // requestForm.value.purchaseInqMaterialDetailLitsRespVos = [];
    // requestForm.value.purchaseProjectListRespVos = [];
    materialAllList.value = [];
    materialAllList.value = JSON.parse(JSON.stringify(res));
    requestForm.value.purchaseContractMaterialRespVos = res;
    // 回显请购单列表
  }
  // requestList.value = requestForm.value.purchaseInqMaterialDetailLitsRespVos;
  // 请购单列表
  //
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = () => {
  // 预算： 单价*数量
  if (contactForm.value.budgetedPrice && contactForm.value.purchaseNumber) {
    contactForm.value.budgeteAllPrice = (
      contactForm.value.budgetedPrice * contactForm.value.purchaseNumber
    ).toFixed(2);
  }
  // 总金额： 单价*数量+运费
  if (contactForm.value.purchasePrice && contactForm.value.purchaseNumber) {
    let freight = contactForm.value.freight
      ? Number(contactForm.value.freight)
      : 0;
    contactForm.value.allPrice = (
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber +
      freight
    ).toFixed(2);
  }
  // 税额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxRate) {
    contactForm.value.taxAmount = (
      (contactForm.value.purchasePrice /
        (1 + contactForm.value.taxRate * 0.01)) *
      contactForm.value.taxRate *
      0.01
    ).toFixed(2);
  }

  // 不含税金额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxAmount) {
    contactForm.value.noTaxAmount = (
      contactForm.value.purchasePrice - contactForm.value.taxAmount
    ).toFixed(2);
  }
};

/**
 * @description: 处理服务时间计算
 * @param {Number} value 选择值
 */
const handleServeTime = (flag) => {
  if (requestForm.value.startDate && requestForm.value.expirationDate) {
    let time1 = new Date(requestForm.value.startDate).getTime();
    let time2 = new Date(requestForm.value.expirationDate).getTime();
    if (time2 < time1) {
      if (flag == 1) {
        requestForm.value.startDate = "";
      } else {
        requestForm.value.expirationDate = "";
      }
      requestForm.value.serviceTime = "";
      return ElMessage.warning("截止日期不能早于起始日期");
    }
    requestForm.value.serviceTime = dateDiffInDays(
      requestForm.value.startDate,
      requestForm.value.expirationDate
    );
  }
  function dateDiffInDays(startDate, endDate) {
    startDate = new Date(startDate);
    endDate = new Date(endDate);
    let timeDiff = Math.abs(endDate - startDate),
      daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
    return daysDiff;
  }
};

/**
 * @description: 计算变动金额
 * @param {Number} value 选择值
 */
const handleChangePrice = () => {
  // 现合同金额： 原合同金额 + 变动金额
  if (requestForm.value.changeMoney && requestForm.value.contractAmount) {
    requestForm.value.newContractMoney =
      Number(requestForm.value.contractAmount) +
      Number(requestForm.value.changeMoney);
  }
};

/**
 * @description: 新增到票
 */
const handleAddTicket = () => {
  ticketPageType.value = "add";
  requestAddShow.value = true;
};

/**
 * @description: 新增付款申请
 */
const handleAddPayment = () => {
  paymentPageType.value = "add";
  paymentAddShow.value = true;
};

/**
 * @description: 新增入库
 */
const handleAddInorder = () => {
  inorderPageType.value = "add";
  inorderAddShow.value = true;
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        requestForm.value.purchaseContractMaterialRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        requestForm.value.purchaseContractMaterialRespVos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      nextTick(() => {
        refInput.value.focus();
        if (operateType.value == "edit") {
          contactAddShow.value = false;
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestFormRef.value.clearValidate("suppFileInfoVos");
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 7 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  if (data) {
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = "合计";
        return;
      }
      const values = data.map((item) => Number(item[column.property]));
      // 只对amount这一列进行总计核算。
      if (
        column.property === "purchaseNumber" ||
        column.property === "budgetedPrice" ||
        column.property === "purchasePrice" ||
        // column.property === "taxRate" ||
        column.property === "taxAmount" ||
        column.property === "freight" ||
        column.property === "noTaxAmount" ||
        column.property === "allPrice" ||
        column.property === "budgeteAllPrice"
      ) {
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.property !== "purchaseNumber") {
            sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
          }
          // sums[index] += "元";
        } else {
          sums[index] = "";
        }
      }
    });
    if (props.pageType === "add" || props.pageType === "edit") {
      // sums[16] = sums[11] * sums[8] + sums[15];
      // sums[10] = sums[9] * sums[8];
      // sums[15] = null;
      // 14总价 9单价 6数量
      // sums[15] = sums[10] * sums[7] + sums[14];
      // sums[9] = sums[8] * sums[7];
      // sums[14] = null;
    } else {
      // sums[16] = sums[11] * sums[8] + sums[15];
      // sums[10] = sums[9] * sums[8];
      // sums[15] = null;
      // 14总价 9单价 6数量
      // sums[15] = sums[10] * sums[7] + sums[14];
      // sums[9] = sums[8] * sums[7];
      // sums[14] = null;
    }
    return sums;
  }
};

/**
 * @description: 处理合计
 */
const getSummariesTicket = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (column.property === "invoiceAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

/**
 * @description: 处理本次使用数量
 */
const handleQuantity = (row, index) => {
  if (Number(row.quantity) < 0) {
    requestForm.value.purchaseConMaterialByIdRespVos[index].quantity = 0;
  }
  if (Number(row.quantity) > Number(row.remainingQuantity)) {
    requestForm.value.purchaseConMaterialByIdRespVos[index].quantity = Number(
      row.remainingQuantity
    );
  }
};

/**
 * @description: 处理合计
 */
const getSummariesPaymentList = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (data && data.length) {
      const values = data.map((item) => Number(item[column.property]));
    }
    // 只对amount这一列进行总计核算。
    if (column.property === "invoiceAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

/**
 * @description: 付款记录表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handlePayOperate = async (type, row) => {
  switch (type) {
    case "edit":
      paymentPageType.value = type;
      paymentAddShow.value = true;
      nextTick(() => {
        paymentAddRef.value.handleDetailInfo(row.paymentApplyId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该付款申请信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deletePaymentId(row.paymentApplyId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            handleDetailInfo(sealId.value);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleTicketOperate = async (type, row) => {
  switch (type) {
    case "edit":
      ticketPageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.contractRelationInvoiceId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该到票信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteTicketApi(row.contractRelationInvoiceId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getTicketList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  // getDicts();

  sealId.value = id;
  try {
    detailInfoShow.value = true;
    // 合同用印详情接口
    const res = await getSealDetailApi(id);
    
    if (res) {
      requestForm.value = {...res,suppFileInfoVos:res.suppFileInfoVos || [],archiveFileList:res.archiveFileList || []}
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理到票
 * @param {Number} id
 */
const getTicketList = async () => {
  // 合同用印到票列表
  await getTicketListApi(requestForm.value.purchaseContractId).then((res) => {
    if (res) {
      ticketList.value = res;
    }
  });
};


/**
 * @description: 获取字典
 */
async function getDicts() {
  // 类型
  await getDictsApi("erp_synthesis_contract_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });



  // 甲方单位
  await getDictsApi("erp_ownership_seal").then((res) => {
    if (res.code === 200) {
      partyUnitsList.value = res.data;
    }
  });
  await getCustomerAllListApi().then((res) => {
    customerList.value = res;
  });

 
  



  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });
 

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}


onMounted(() => {
  if(route.name === 'Strategy') {
    contentType.value = 6
  }else {
    contentType.value = 7
  }
  getDicts();
  // if (props.pageType === "add") {
  //   nextTick(() => {
  //     refSelect.value.focus();
  //   });
  // }
  // if (props.pageType === "add") {
  //   requestForm.value.handleId = userStore.id;
  // }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
  background-color: #fff;
}
.auto-item {
  width: 130px;
  text-align: left;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
:deep(.el-form-item--default) {
  margin-bottom: 22px;
}
:deep(.el-form-item--default .el-form-item__error) {
  padding-top: 5px;
}
.disabled-bg {
  background-color: #f5f7fa;
}
</style>
